package org.zero.onlinesubject.handler;

import org.zero.onlinesubject.utils.ProcUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;


public class MediaConvertHandler {

    private static String ffmpegPath;

    private static final String subfix = " -hide_banner";

    static {
        init();
    }

    private static void init(){
        InputStream is = MediaConvertHandler.class.getClassLoader().getResourceAsStream("app.properties");
        Properties prop = new Properties();
        try {
            prop.load(is);
            ffmpegPath = prop.getProperty("ffmpeg.path") + " ";
        } catch (IOException e) {
            System.out.println("异常: "+e.getMessage());
        }
    }

    public static void executeCmd(String cmdText){
        Process p = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;
        try {
            p = Runtime.getRuntime().exec(ffmpegPath + cmdText + subfix);

            ProcUtil.add(p);
            isr = new InputStreamReader(p.getErrorStream());
            reader = new BufferedReader(isr);
            String strLine;
            while((strLine = reader.readLine())!=null){
                System.out.println(strLine);
            }
        } catch (IOException e) {
            System.out.println("异常: "+e.getMessage());
        }finally {
            release(p,reader,isr);
        }
    }

    private static void release(Process p,BufferedReader reader,InputStreamReader isr){
        if(p!=null && p.isAlive()){
            p.destroy();
            ProcUtil.remove(p);
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (isr != null) {
                isr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            ProcUtil.destoryAll();
        }));
        String source = "C:/Users/phantom/Desktop/nginxMarkDown/nginx-1.18.0/html/static/webm/42444326.webm";
        String dest = "C:/Users/phantom/Desktop/nginxMarkDown/nginx-1.18.0/html/static/video/42444326.mp4";
        String cmdText =  "-i " + source + " -preset fast -crf 22 -threads 2 -y " + dest;
    }
}

